import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import api from '@/utils/api'

interface UserInfo {
  id: number
  username: string
  email?: string
  phone?: string
  role: string
}

export const useAuthStore = defineStore('auth', () => {
  const accessToken = ref<string | null>(localStorage.getItem('accessToken'))
  const refreshToken = ref<string | null>(localStorage.getItem('refreshToken'))
  const userInfo = ref<UserInfo | null>(null)

  const isAuthenticated = computed(() => !!accessToken.value)

  // 设置token
  function setTokens(access: string, refresh: string) {
    accessToken.value = access
    refreshToken.value = refresh
    localStorage.setItem('accessToken', access)
    localStorage.setItem('refreshToken', refresh)
  }

  // 设置用户信息
  function setUserInfo(info: UserInfo) {
    userInfo.value = info
  }

  // 清除token和用户信息
  function clearAuth() {
    accessToken.value = null
    refreshToken.value = null
    userInfo.value = null
    localStorage.removeItem('accessToken')
    localStorage.removeItem('refreshToken')
  }

  // 更新access token
  function updateAccessToken(token: string) {
    accessToken.value = token
    localStorage.setItem('accessToken', token)
  }

  // 刷新token
  async function refreshAccessToken(): Promise<boolean> {
    if (!refreshToken.value) {
      return false
    }

    try {
      const response = await api.post('/auth/refresh', {
        refreshToken: refreshToken.value
      })

      if (response.data.code === 200) {
        updateAccessToken(response.data.data)
        return true
      }
      return false
    } catch (error) {
      console.error('刷新token失败:', error)
      clearAuth()
      return false
    }
  }

  // 获取用户信息
  async function fetchUserInfo() {
    try {
      const response = await api.get('/auth/me')
      if (response.data.code === 200) {
        setUserInfo(response.data.data)
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  }

  // 注册
  async function register(username: string, password: string, email?: string, phone?: string) {
    try {
      const response = await api.post('/auth/register', {
        username,
        password,
        email,
        phone
      })

      if (response.data.code === 200) {
        const data = response.data.data
        setTokens(data.accessToken, data.refreshToken)
        setUserInfo(data.userInfo)
        return true
      }
      return false
    } catch (error: any) {
      console.error('注册失败:', error)
      throw error
    }
  }

  // 登录
  async function login(username: string, password: string) {
    try {
      const response = await api.post('/auth/login', {
        username,
        password
      })

      if (response.data.code === 200) {
        const data = response.data.data
        setTokens(data.accessToken, data.refreshToken)
        setUserInfo(data.userInfo)
        return true
      }
      return false
    } catch (error: any) {
      console.error('登录失败:', error)
      throw error
    }
  }

  // 退出登录
  async function logout() {
    try {
      if (refreshToken.value) {
        await api.post('/auth/logout', null, {
          headers: {
            'Refresh-Token': refreshToken.value
          }
        })
      }
    } catch (error) {
      console.error('退出登录失败:', error)
    } finally {
      clearAuth()
    }
  }

  return {
    accessToken,
    refreshToken,
    userInfo,
    isAuthenticated,
    setTokens,
    setUserInfo,
    clearAuth,
    updateAccessToken,
    refreshAccessToken,
    fetchUserInfo,
    register,
    login,
    logout
  }
})

